import React, { useEffect, useState, useRef } from "react";
import {
  Select,
  DatePicker,
  Button,
  Space,
  Form,
  Input,
  Radio,
  Table,
  message,
} from "antd";
import { SearchOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import api from "../../utils/api";
import { Saffix, Smodal } from "../../conponents/index";
import { useForm } from "antd/es/form/Form";
import useLoading from "@/hooks/useLoading";
const FilterLayout = () => {
  useEffect(() => {
    loadData();
  }, []);
  const [loading, setLoading] = useLoading();
  const { Option } = Select;
  const [form] = Form.useForm();
  const defauleTimeArray = () => [dayjs().startOf("week"), dayjs()];
  const initialValues = {
    user_name: "",
    is_admin: 2,
    create_At: defauleTimeArray(),
    state: 2,
  };

  const loadData = async () => {
    setLoading(true);
    const { create_At, ...res } = form.getFieldsValue();
    let startTime = null;
    let endTime = null;
    if (Array.isArray(create_At) && create_At.length === 2) {
      startTime = create_At[0].format("YYYY-MM-DD HH:mm:ss");
      endTime = create_At[1].format("YYYY-MM-DD HH:mm:ss");
    } else {
      startTime = dayjs().subtract(3, "year").format("YYYY-MM-DD HH:mm:ss");
      endTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    }
    try {
      const {
        data: { list = [] },
      } = await api.getUserList({ ...res, startTime, endTime });
      setData(
        list.map((/** @type {{ id: any; }} */ v) => ({ ...v, key: v.id }))
      );
    } catch (e) {
      console.log("error", e);
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: "账号",
      dataIndex: "user_name",
      key: "user_name",
      minWidth: 100,
      render: (text) => <a>{text}</a>,
    },
    {
      title: "创建时间",
      dataIndex: "create_at",
      key: "create_at",
      minWidth: 100,
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      minWidth: 100,
      render: (v, record) => {
        return <>{v === 0 ? "否" : "是"}</>;
      },
    },
    {
      title: "是否管理员",
      key: "is_admin",
      dataIndex: "is_admin",
      minWidth: 130,
      render: (_, record) => {
        return _ === 0 ? "否" : "是";
      },
    },
    {
      title: "动作",
      key: "action",
      minWidth: 130,
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => setInvalidUsers(_)}>
            {_.state === 0 ? "恢复" : "失效"}
          </Button>
          <Button type="link" onClick={() => editUser(_)}>
            编辑
          </Button>
          <Button type="link" onClick={() => deleteUser(_)}>
            删除
          </Button>
          <Button type="link">重置密码</Button>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([]);

  const { RangePicker } = DatePicker;

  const adduserModalref = useRef(null);

  const adduser = () => adduserModalref.current.open();

  const editUser = (value) => {
    adduserModalref.current.open();
    adduserForm.setFieldsValue(value);
  };
  // 失效用户 or 恢复用户
  const setInvalidUsers = async (value) => {
    const { data } = await api.setInvalidUser(value.id);
    messageApi.open({
      type: data.type,
      content: data.msg,
    });
    loadData();
  };

  const deleteUser = async ({ id }) => {
    const { data } = await api.deleteUser({ id });
    messageApi.open({
      type: data.type,
      content: data.msg,
    });
    loadData();
  };

  const [adduserForm] = useForm();
  const adduserFormFinish = async () => {
    const values = adduserForm.getFieldsValue();
    const { data } = await api.addUser(values);
    messageApi.open({
      type: data.type,
      content: data.msg,
    });
    adduserForm.resetFields();
    adduserModalref.current.close();
    loadData();
  };
  const adduserFormOk = async () => {
    adduserForm.submit();
  };
  const [messageApi, contextHolder] = message.useMessage();
  return (
    <>
      {contextHolder}
      <div className="search_wrapper">
        <Form form={form} layout="inline" initialValues={initialValues}>
          <Form.Item name="state">
            <Select style={{ width: 160 }} placeholder="状态">
              {Array.from(
                [
                  {
                    label: "失效",
                    value: 0,
                  },
                  {
                    label: "正常",
                    value: 1,
                  },
                  {
                    label: "全部",
                    value: 2,
                  },
                ],
                function (item) {
                  return (
                    <Option value={item.value} key={item.value}>
                      {item.label}
                    </Option>
                  );
                }
              )}
            </Select>
          </Form.Item>
          <Form.Item name="create_At">
            <RangePicker format="YYYY-MM-DD HH:mm:ss" placeholder="创建时间" />
          </Form.Item>
          <Form.Item name="user_name">
            <Input placeholder="账号(忽略其他搜索条件)" allowClear />
          </Form.Item>
          <Form.Item name="is_admin">
            <Radio.Group buttonStyle="solid">
              {[
                {
                  label: "普通用户",
                  value: 0,
                },
                {
                  label: "管理员",
                  value: 1,
                },
                {
                  label: "全部",
                  value: 2,
                },
              ].map((item) => (
                <Radio.Button value={item.value} key={item.value}>
                  {item.label}
                </Radio.Button>
              ))}
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              onClick={loadData}
            />
          </Form.Item>
        </Form>
      </div>
      <div className="affix-wrapper">
        <Saffix>
          <Space>
            <Button onClick={adduser}>新增</Button>
            <Button>批量删除</Button>
          </Space>
        </Saffix>
      </div>
      <div className="table_wrapper">
        <Table
          style={{
            minHeight: 1800,
          }}
          loading={loading}
          dataSource={data}
          columns={columns}
          pagination={{
            position: ["bottomRight"],
          }}
        />
      </div>
      <Smodal
        title="新增用户"
        ref={adduserModalref}
        onCancel={() => adduserModalref.current.close()}
        onOk={adduserFormOk}
      >
        <Form
          form={adduserForm}
          name="adduserForm"
          onFinish={adduserFormFinish}
        >
          <Form.Item
            label="账号"
            name="user_name"
            rules={[
              {
                required: true,
                message: "请输入账号!",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                required: true,
                message: "请输入密码!",
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="是否管理员"
            name="is_admin"
            rules={[
              {
                required: true,
                message: "请输入选择是否是管理员!",
              },
            ]}
            initialValue={0}
          >
            <Radio.Group buttonStyle="solid">
              <Radio.Button value={0}>否</Radio.Button>
              <Radio.Button value={1}>是</Radio.Button>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Smodal>
    </>
  );
};

export default FilterLayout;
